package com.stylefeng.guns.rest.modular.wz.api.v1;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.rest.common.base.controller.ApiBaseController;
import com.stylefeng.guns.rest.common.constant.Consts;
import com.stylefeng.guns.rest.common.constant.WzConsts;
import com.stylefeng.guns.rest.common.exception.BizExceptionEnum;
import com.stylefeng.guns.rest.common.persistence.dao.*;
import com.stylefeng.guns.rest.common.persistence.model.*;
import com.stylefeng.guns.rest.common.util.StringUtils;
import com.stylefeng.guns.rest.domain.ParamMap;
import com.stylefeng.guns.rest.domain.Res;
import com.stylefeng.guns.rest.enums.EnWzAdv;
import com.stylefeng.guns.rest.enums.EnWzUser;
import com.stylefeng.guns.rest.enums.EnWzUserFinanceRecord;
import com.stylefeng.guns.rest.modular.auth.util.JwtTokenUtil;
import com.stylefeng.guns.rest.modular.wz.cache.CacheService;
import com.stylefeng.guns.rest.modular.wz.controller.AsyncService;
import com.stylefeng.guns.rest.modular.wz.service.impl.WzUserServiceImpl;
import com.stylefeng.guns.rest.modular.wz.util.wz.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户表
 */
@RestController
@RequestMapping("/wz/api/v1/wzUser/")
public class WzUserApi extends ApiBaseController {
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private WzUserMapper userMapper;
    @Autowired
    private WzPrizeMapper prizeMapper;
    @Autowired
    private WzPrizeWinnersMapper prizeWinnersMapper;
    @Autowired
    private WzUserFinanceRecordMapper userFinanceRecordMapper;
    @Autowired
    private WzUserCouponMapper userCouponMapper;
    @Autowired
    private WzUserServiceImpl userService;
    @Autowired
    private WzCouponMapper couponMapper;
    @Autowired
    private WzUserInfoMapper userInfoMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private AsyncService asyncService;
    @Autowired
    private WzConsts wzConsts;
    @Autowired
    private WzUserFixedInfoMapper userFixedInfoMapper;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private WzAdvShareMapper advShareMapper;
    @Autowired
    private WzAdvMapper advMapper;
    @Autowired
    private WzUserAdvRecordMapper userAdvRecordMapper;
    /**
     * 修改用户定位信息
     */
    @PostMapping("location.update")
    public Res locationUpdate(@RequestBody ParamMap paramMap) throws Exception{
        String adCode = paramMap.getStrMisValid("adCode");
        String longitude = paramMap.getStrMisValid("longitude");
        String latitude = paramMap.getStrMisValid("latitude");
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        WzUser user = cacheService.user(userCode);
//        if(userCode == 1007804146831298561L){
//            adCode = "320482";
//        }
        user.setAdCode(adCode);
        user.setUpdateTime(new Date());
        user.setLongitude(longitude);
        user.setLatitude(latitude);
        userMapper.updateById(user);
        return Res.success();
    }

    /**
     * 用户基本信息
     */
    @PostMapping("basicInfo")
    public Res basicInfo(@RequestBody ParamMap paramMap) throws Exception{
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        Map<String,Object> map = cacheService.userBasicInfo(userCode);
        paramMap.parseMap(map);
        SysUser sysUser = cacheService.sysUser(paramMap.get("account").toString());
        if(sysUser == null){
            paramMap.put("adminRole","0");
        }else{
            paramMap.put("adminRole",sysUser.getRoleid());
        }
        WzUser user = cacheService.user(userCode);
        boolean r = false;
        if(!StringUtils.isBlankStr(paramMap.getStr("mobileType"))){
            if(user.getMobileType() != paramMap.getInt("mobileType")){
                user.setMobileType(paramMap.getInt("mobileType"));
                user.setUpdateTime(new Date());
                r = true;
            }
        }
        if(!StringUtils.isBlankStr(paramMap.getStr("iosVersion"))){
            if(!paramMap.getStr("iosVersion").equals(user.getMobileVersion())){
                user.setMobileVersion(paramMap.getStr("iosVersion"));
                user.setUpdateTime(new Date());
                r = true;
            }
            String now = DateUtil.toString(new Date());
            String time = DateUtil.toString(user.getUpdateTime());
            if(!now.equals(time)){
                user.setUpdateTime(new Date());
                r = true;
            }
        }
        if(!StringUtils.isBlankStr(paramMap.getStr("androidVersion"))){
            if(!paramMap.getStr("androidVersion").equals(user.getMobileVersion())){
                user.setMobileVersion(paramMap.getStr("androidVersion"));
                user.setUpdateTime(new Date());
                r = true;
            }
            String now = DateUtil.toString(new Date());
            String time = DateUtil.toString(user.getUpdateTime());
            if(!now.equals(time)){
                user.setUpdateTime(new Date());
                r = true;
            }
        }
        if(r){
            userMapper.updateById(user);
        }
        return Res.success(paramMap);
    }

    /**
     * 钱包账户记录
     */
    @PostMapping("wallet.finance.record")
    public Res userFinanceRecord(@RequestBody ParamMap paramMap){
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        //查询用户资金记录
        String sql = "amount As amount,type As type,title As title,pay_time As payTime";
        List<Map<String,Object>>  list = userFinanceRecordMapper.selectMapsPage(new Page<>(pageNum,pageSize),new EntityWrapper<WzUserFinanceRecord>().setSqlSelect(sql).eq("user_code",userCode).orderBy("pay_time",false).ne("status",EnWzUserFinanceRecord.STATUS_hidden.getIndex()));
        paramMap.put("list",list);
        return Res.success(paramMap);
    }

    /**
     * 钱包
     * 充值
     */
    @PostMapping("wallet.recharge")
    public Res userRecharge(@RequestBody ParamMap paramMap) throws Exception{
        //参数校验
        String amount = paramMap.getStrMisValid("amount");
        String payMethod = paramMap.getStrMisValid("payMethod");
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        WzUser user = cacheService.user(userCode);
        //苹果审核
        String iosVersion = paramMap.getStr("iosVersion");
        Map<String,Object> sys = cacheService.commomSys("commomSys");
        if(sys.get("ios_status").toString().equals("0") && sys.get("ios_check_version").toString().equals(iosVersion)){//判断是否在苹果审核状态
            System.out.println("ceshi");
        }
        //业务处理
        Res res = userService.recharge(paramMap,userCode);
        return res;
    }

    /**
     * 钱包
     * 提现
     */
    @PostMapping("wallet.withdrawals")
    public Res userWithdrawals(@RequestBody ParamMap paramMap) throws Exception{
        int amount = paramMap.getIntMisValid("amount");
        String payMethod = paramMap.getStrMisValid("payMethod");
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        List<WzUser > userList = userMapper.selectList(new EntityWrapper<WzUser>().eq("user_code",userCode));
        if(amount > userList.get(0).getRewardBalance()){
            return Res.fail("积分余额不足!");
        }
        if(userList.get(0).getStatus() == 0){
            return Res.fail("账户资金异常，冻结中!");
        }
        if (amount < Integer.parseInt(Consts.cashLimit)) {
            return Res.fail("提现金额需大于等于3");
        }
//        if(userList.get(0).getUserCode().toString().equals("1054981877184819201")){//分享数据异常
//            return Res.fail("分享数据异常处理中，无法体现!");
//        }
        String androidVersion = paramMap.getStrValid("androidVersion");
        String iosVersion = paramMap.getStrValid("iosVersion");
        boolean rr = true;
        if(!StringUtils.isBlankStr(iosVersion)){
            int ios = Integer.parseInt(iosVersion.substring(0,1))*100 + Integer.parseInt(iosVersion.substring(2,3))*10 + Integer.parseInt(iosVersion.substring(4,5));
            if(ios >= Integer.parseInt(Consts.iosVersion)){
                rr = false;
            }
        }
        if(!StringUtils.isBlankStr(androidVersion)){
            int a = Integer.parseInt(androidVersion);
            if(a >= Integer.parseInt(Consts.androidVersion)){
                rr = false;
            }
        }
        if(rr){
            return Res.fail("版本太低无法提现，请更新!");
        }
        if(Consts.dev.equals("true")){
            return  Res.fail("测试中不可提现!");
        }
        //用户固定信息
        List<WzUserFixedInfo> userFixedInfos = userFixedInfoMapper.selectList(new EntityWrapper<WzUserFixedInfo>().eq("user_code",userCode));
        if(payMethod.equals(EnWzUserFinanceRecord.payMethod_alipay.getName())) {//支付宝提现
            if (StringUtils.isBlankStr(userFixedInfos.get(0).getAlipayUserId())) {
                return Res.fail("还未绑定支付宝");
            }
        }else if(payMethod.equals(EnWzUserFinanceRecord.payMethod_weixin.getName())) {//微信提现
            if (StringUtils.isBlankStr(userFixedInfos.get(0).getWeixinOpenid())) {
                return Res.fail("还未绑定微信");
            }
        }
        //每日提现一次
        String a = DateUtil.toString(new Date());
        String b = DateUtil.toString(DateUtil.nextDay(new Date()));
        int t = userFinanceRecordMapper.selectCount(new EntityWrapper<WzUserFinanceRecord>().between("pay_time",a,b).in("status",new Integer[]{EnWzUserFinanceRecord.STATUS_waitCheck.getIndex(),EnWzUserFinanceRecord.STATUS_SUCCESS.getIndex(),EnWzUserFinanceRecord.STATUS_WAIT_CHECK.getIndex()})
                .in("pay_type",new Integer[]{EnWzUserFinanceRecord.TITLE_alipay_withdrawals.getIndex(),EnWzUserFinanceRecord.TITLE_wexin_withdrawals.getIndex()}).eq("user_code",userCode));
        if(t >= wzConsts.getDailyCashNumber()){
            return Res.fail(BizExceptionEnum.CASH_NUMBER_DAY);
        }
        //每次提现限额
        if(userList.get(0).getHasAdvMap() == 0){
            if(amount > wzConsts.getCashDayLimit()*100){
                return Res.fail(BizExceptionEnum.CASH_NUMBER_DAY.getCode(),"每次提现限额"+wzConsts.getCashDayLimit());
            }
        }
        if(userList.get(0).getHasAdvMap() == 1){
            if(amount > Integer.parseInt(Consts.merchantCashDayLimit)*100){
                return Res.fail(BizExceptionEnum.CASH_NUMBER_DAY.getCode(),"每次提现限额"+Consts.merchantCashDayLimit);
            }
        }
        //提现实名认证
        if(userList.get(0).getRole() < EnWzUser.ROLE_RealName.getIndex()){
            //提现满5次需实名认证
            int r = userFinanceRecordMapper.selectCount(new EntityWrapper<WzUserFinanceRecord>().in("pay_type",new Integer[]{EnWzUserFinanceRecord.TITLE_alipay_withdrawals.getIndex(),EnWzUserFinanceRecord.TITLE_wexin_withdrawals.getIndex()})
                    .in("status",new Integer[]{EnWzUserFinanceRecord.STATUS_SUCCESS.getIndex(),EnWzUserFinanceRecord.STATUS_WAIT_CHECK.getIndex()}).eq("user_code",userCode));
            r = r + 1;
            if(r > wzConsts.getCashNumberBeforeAuthentication() && userList.get(0).getRole() < EnWzUser.ROLE_RealName.getIndex()){
                if(userList.get(0).getRole() == EnWzUser.ROLE_USER.getIndex() && userList.get(0).getStatus() == EnWzUser.STATUS_RealName_WaitCheck.getIndex()){
                    return Res.fail("实名认证审核中!");
                }
                return Res.fail(BizExceptionEnum.NOT_REAL_NAME.getCode(),"提现满"+wzConsts.getCashNumberBeforeAuthentication()+"次需实名认证");
            }
            //提现满50需实名认证
            //每次提现限额
            if(amount > wzConsts.getCashLimit()*100){
                return Res.fail(BizExceptionEnum.NOT_REAL_NAME_CASH_LIMIT.getCode(),"提现满"+wzConsts.getCashLimit()+"元需实名认证");
            }
            List<Map<String,Object>> amountSum = userFinanceRecordMapper.selectMaps(Condition.create().setSqlSelect("sum(amount) as amount").in("pay_type",new Integer[]{6,7}).eq("status",1).eq("user_code",userCode));
            if(amountSum.get(0) != null && r > 0){
                int aa = Integer.parseInt(amountSum.get(0).get("amount").toString()) + amount;
                if(aa > wzConsts.getCashLimit()*100){
                    return Res.fail(BizExceptionEnum.NOT_REAL_NAME_CASH_LIMIT.getCode(),"提现满"+wzConsts.getCashLimit()+"元需实名认证");
                }
            }
        }
        //业务处理
        Res res = userService.withdrawals(paramMap,userList.get(0),userFixedInfos.get(0));
        return res;
    }

    /**
     * 礼券
     */
    @PostMapping("user.coupon")
    public Res userCoupon(@RequestBody ParamMap paramMap){
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        //业务处理
        Res res = userService.userCoupon(paramMap,userCode);
        return res;
    }

    /**
     * 我的礼券
     */
    @PostMapping("userCoupon")
    public Res userCoupons(@RequestBody ParamMap paramMap){
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        int status = paramMap.getIntMisValid("status");//状态:1-可用;2-已使用;3-过期
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        //业务处理
        Res res = userService.userCoupons(paramMap,userCode);
        return res;
    }

    /**
     * 礼券详情
     */
    @PostMapping("couponDetail")
    public Res couponDetail(@RequestBody ParamMap paramMap){
        String couponId = paramMap.getStrMisValid("couponId");
        //礼券
        String sql = "coupon_id As couponId,adv_map_id As advMapId,rule,benefit,type,subtype,begin_time As beginTime,end_time As endTime,pic,reject_remark AS rejectRemark";
        List<Map<String,Object>>  couponList = couponMapper.selectMaps(new EntityWrapper<WzCoupon>().setSqlSelect(sql).eq("coupon_id",couponId));
        Map<String,Object> coupon=couponList.get(0);
        WzAdvMap advMap=cacheService.advMap(Long.parseLong(coupon.get("advMapId").toString()));
        coupon.put("logo",advMap.getLogo());
        coupon.put("name",advMap.getName());
        coupon.put("merchantTel",advMap.getMerchantTel());
        coupon.put("longitude",advMap.getLongitude());
        coupon.put("latitude",advMap.getLatitude());
        coupon.put("merchantAddress",advMap.getMerchantFullAddress());
        paramMap.putAll(coupon);
        return Res.success(paramMap);
    }

    /**
     * 我的广告记录
     */
    @PostMapping("adv.record")
    public Res advRecord(@RequestBody ParamMap paramMap){
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        //业务处理
        Res res = userService.advRecord(paramMap,userCode);
        return res;
    }

    /**
     * 消息中心
     */
    @PostMapping("messageList")
    public Res messageList(@RequestBody ParamMap paramMap){
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        int sendType = paramMap.getIntMisValid("sendType");
        //业务处理
        Res res = userService.messageList(paramMap,sendType);
        return res;
    }

    /**
     * 消息详情
     */
    @PostMapping("messageRead")
    public Res messageRead(@RequestBody ParamMap paramMap){
        String userMessageId = paramMap.getStrMisValid("userMessageId");
        //业务处理
        Res res = userService.messageRead(paramMap);
        return res;
    }
}

